<template>
  <q-page class="q-pa-md">







    <q-form @submit.prevent="addQueryAndSearch">
      <q-select
        v-model="queryInput"
        :options="filteredOptions"
        label="输入告警内容"
        use-input
        fill-input
        input-debounce="500"
        @filter="filterOptions"
        dense
        filled
        class="q-mb-md"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              无匹配内容
            </q-item-section>
          </q-item>
        </template>
      </q-select>
      <q-btn type="submit" label="分析" color="primary" class="q-ml-md"/>
    </q-form>




<!--    -->
<!--    <q-form @submit.prevent="addQuery">-->
<!--      <q-input-->
<!--        v-model="queryInput"-->
<!--        label="输入查询内容"-->
<!--        dense-->
<!--        filled-->
<!--        class="q-mb-md"-->
<!--      />-->
<!--      <q-btn type="submit" label="查询" color="primary" class="q-ml-md" />-->
<!--    </q-form>-->

    <div v-if="queries.length">
      <h3>告警业务</h3>
      <div>
        <q-chip
          v-for="(query, index) in queries"
          :key="index"
          removable
          @remove="removeQuery(index)"
          class="q-mr-md q-mb-md"
        >
          {{ query }}
        </q-chip>
      </div>
    </div>

    <div v-if="result">
      <h3>预警光缆诊断结果</h3>
      <p>{{ result }}</p>


      <q-card>
        <q-card-section>
          <div class="text-h6">当前诊断结果</div>
        </q-card-section>
        <q-card-section>
          <pre>{{ this.formattedJson }}</pre>
        </q-card-section>
      </q-card>
    </div>
  </q-page>
</template>

<script>
import axios from 'axios';
export default {
  data() {
    return {
      formattedJson: [
        { "所属光缆": "光缆1", "数量": 10 },
        { "所属光缆": "光缆2", "数量": 15 }
      ],
      filteredOptions: [],  // 过滤后的选项
      ywNames:'',
      queryInput: '',
      queries: [],
      result: ''
    };
  },
  methods: {
    async addQueryAndSearch() {
      if (this.queryInput) {
        this.queries.push(this.queryInput);
        this.queryInput = '';
        await this.search(); // 在添加查询后立即执行搜索
      }
    },
    filterOptions(val, update) {
      update(() => {
        if (val) {
          const filter = new RegExp(val, 'i')
          this.filteredOptions = this.ywNames.filter(v => v.match(filter))
        } else {
          this.filteredOptions = this.ywNames
        }
      });
    },
    addQuery() {
      if (this.queryInput) {
        this.queries.push(this.queryInput);
        this.queryInput = '';
        // this.search();
      }
    },
    removeQuery(index) {

      this.queries.splice(index, 1);
      this.search();
    },
    async search() {




    try {
        // 发送 GET 请求并等待响应
        // 将条件传过去就ok了 当前输入数组内容作为参数传入。
        console.log(this.queries)
        const response = await axios.get('http://127.0.0.1:4444/get_xiangtongyongtu_names', {
        params: { items_yw: JSON.stringify(this.queries) }  // 确保键名与后端匹配
      });
        // 处理成功情况



        console.log('Road names:', response.data.road_names);
        // this.result = `当前诊断结果: ${JSON.stringify({"所属光缆":response.data[0]['所属光缆'],"统计值":response.data[0]['数量']})}`;
        // localStorage.setItem('渲染',JSON.stringify(response.data[0]))
      const responseData = response.data;

// 创建一个新数组，用于存储处理后的数据
      const processedData = responseData.map(item => ({
        "所属光缆": item['所属光缆'],
        "故障分析值": item['数量']
      }));

      this.formattedJson = processedData;

// 将处理后的数据数组转换为JSON字符串并展示
      this.result = `当前诊断结果: ${JSON.stringify(processedData)}`;

// 将处理后的数据数组存储到 localStorage 中
      localStorage.setItem('渲染', JSON.stringify(responseData));


        return ;
    } catch (error) {
        // 处理错误情况
        console.error('Error fetching data:', error);
    }



      console.log("search")
      const uniqueItems = {};
      const data = [];
      var queriesq = []
      console.log(this.queries)




      for (const query1 of this.queries) {
        queriesq = []
        queriesq.push(query1)
          console.log(query1)
          if (queriesq.length>0) {
          if (!queriesq.includes("SDH")) {
                queriesq.push("SDH");
              }
          // 构建查询条件
          const mustQueries = queriesq.map(condition => ({
            match_phrase: {
              "对应光路": condition
            }
          }));

          // 构建最终查询
          const query = {
            bool: {
              must: mustQueries
            }
          };

          try {
            // 发送查询请求
            const response = await axios.post(
              'http://1.95.80.5:9002/xianmen_guanglu/_search',  // 修改IP地址
              {
                query: query,
               "size": 0,
                "aggs": {
                  "by_belonging_cable": {
                    "terms": {
                      "field": "所属光缆.keyword"
                    },
                    "aggs": {
                      "unique_routes": {
                        "cardinality": {
                          "field": "对应光路.keyword"
                        }
                      }
                    }
                  },
                  "by_route": {
                    "terms": {
                      "field": "对应光路.keyword"
                    },
                    "aggs": {
                      "unique_cables": {
                        "cardinality": {
                          "field": "所属光缆.keyword"
                        }
                      }
                    }
                  }
                }
              },
              {
                headers: {
                  'Content-Type': 'application/json',
                  'Authorization': 'Basic ' + btoa('admin:1992A1573')
                }
              }
            );

            // // 处理响应数据
            // const hits = response.data.aggregations.by_belonging_cable.buckets;
            // const hits2 = response.data.aggregations.by_route.buckets;
            // const result = hits[0].key;
            // data.push({"key":hits[0].key+"-"+hits2[0].key,"value":hits[0].doc_count})
            //
            const hits = response.data.aggregations.by_belonging_cable.buckets;
            const hits2 = response.data.aggregations.by_route.buckets;
            const data = [];

// 检查两个数组的长度是否一致
            if (hits.length === hits2.length) {
              // 遍历所有元素，并将其push到data数组中
              for (let i = 0; i < hits.length; i++) {
                data.push({
                  "key": hits[i].key + "-" + hits2[i].key,
                  "value": hits[i].doc_count
                });
              }
            } else {
              console.error("Hits and hits2 arrays have different lengths!");
            }

// 输出结果数组
            console.log(data);

          } catch (error) {
            console.error("查询失败:", error);
            this.result = '查询失败';
          }
        } else {
          this.result = '暂无查询内容';
        }
      }


       this.result = `当前诊断结果: ${JSON.stringify(data)}`;



    }
  },
  mounted() {

  // todo 查这个yw_names
    axios.get('http://127.0.0.1:4444/get_yw_names')  // 保 URL 和端口与 Flask 用一致
      .then(response => {
        // 试图手动解析 JSON 数据
        try {
          const data = response.data;  // 手动解析 JSON 字符串
          this.ywNames = data.yw_names;  // 更新业务名称数据
        } catch (e) {
          console.error('解析 JSON 数据时发生错误:', e);
        }
        console.log('业务名称:', this.ywNames);
      })
      .catch(error => {
        console.error('请求业务名称时发生错误:', error);
      });





  }

};
</script>
<style scoped>
pre {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 5px;
  white-space: pre-wrap; /* 自动换行 */
  word-wrap: break-word; /* 支持长单词换行 */
}
</style>
